/**  
 * All rights Reserved, Designed By Android_Robot   
 * @Title:  WorkStatisticsActivity.java   
 * @Package com.jiyi.activity.leader   
 * @Description:    TODO(用一句话描述该文件做什么)   
 * @author: HYM     
 * @date:   2017-9-25 下午4:30:28   
 * @version V1.0     
 */
package com.jiyi.activity.leader;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jiyi.adapter.DividerItemDecoration;
import com.jiyi.adapter.recyclerview.CommonAdapter;
import com.jiyi.adapter.recyclerview.base.ViewHolder;
import com.jiyi.adapter.recyclerview.wrapper.EmptyWrapper;
import com.jiyi.bean.maintenance.WorkStatisticsBean;
import com.jiyi.common.StringInterface;
import com.jiyi.common.VolleyRequest;
import com.jiyi.easemob.util.UserHelp;
import com.jiyi.inteface.WebApi;
import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;
import com.swift.base.ActivityBase;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppBase;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.maintenance.utils.UserInfoUtil;
import com.swift.utils.DateUtils;
import com.swift.utils.MonPickerDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @ClassName: WorkStatisticsActivity
 * @Description:TODO(工作统计)
 * @author: HYM
 * @date: 2017-9-25 下午4:30:28
 * 
 */
public class WorkStatisticsActivity extends ActivityBase implements
		OnRefreshListener ,OnDateSetListener {

	/* 头部 */
	@BindView(R.id.tvBack)
	TextView tvBack;
	@BindView(R.id.tvTitle)
	TextView tvTitle;
	@BindView(R.id.tvSearch)
	TextView tvSearch;

	@BindView(R.id.mainList)
	RecyclerView mListView;
	@BindView(R.id.refreshLayout)
	SwipeRefreshLayout refreshLayout;
	EmptyWrapper adapter;
	private LayoutInflater inflater;

	@BindView(R.id.tvSearchDate)
	TextView tvSearchDate;

	private List<WorkStatisticsBean> mWorkStatistics = new ArrayList<WorkStatisticsBean>();
	private int mYear;
	private int mMonth;
	private int mDay;
	String defaultSearchKeyString = "";
	TimePickerDialog mDialogYearMonth;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_work_statistics);
		ButterKnife.bind(this);
		init();
	}

	private void init() {
		inflater = LayoutInflater.from(this);
		//初始化日期控件
		mDialogYearMonth = new TimePickerDialog.Builder()
				.setTitleStringId("日期选择")
				.setType(Type.YEAR_MONTH)
				.setThemeColor(getResources().getColor(R.color.colorPrimary))
				.setCallBack(WorkStatisticsActivity.this)
				.build();

		setTop();
		initViewState();
		getCurrentYearMouth();
		setAdapter();
		getData(tvSearchDate.getText().toString());
	}

	/**   
	 * @author: HYM 
	 * @Title: getCurrentYearMouth   
	 * @Description: TODO(获取当前年月)    void 
	 * @date: 2017-10-23
	 */  
	private void getCurrentYearMouth() {
		Calendar dateAndTime = Calendar.getInstance(Locale.CHINA);
		mYear = dateAndTime.get(Calendar.YEAR);
		mMonth = dateAndTime.get(Calendar.MONTH)+1;
		mDay = dateAndTime.get(Calendar.DAY_OF_MONTH);
		tvSearchDate.setText(mYear +"-"+ (mMonth <= 9 ? "0"+mMonth:mMonth+""));
	}

	private void setTop() {
		tvTitle.setText("工作统计");
		tvSearch.setVisibility(View.GONE);
	}

	private void initViewState() {
		tvSearchDate.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
//				onCreateDialog().show();



				mDialogYearMonth.show(getSupportFragmentManager(), "year_month");
			}
		});
	}

	private void setAdapter() {
		// 设置refreshLayout的监听
		refreshLayout.setColorSchemeColors(Color.RED, Color.YELLOW, Color.BLUE,
				Color.GREEN);
		refreshLayout.setOnRefreshListener(this);

		mListView.setLayoutManager(new LinearLayoutManager(this));
		mListView.addItemDecoration(new DividerItemDecoration(this,
				DividerItemDecoration.VERTICAL_LIST, getResources()
						.getDrawable(R.drawable.drvice_10)));

		CommonAdapter mCommonAdapter = new CommonAdapter<WorkStatisticsBean>(
				this, R.layout.item_work_statistics, mWorkStatistics) {
			@Override
			protected void convert(ViewHolder holder,
					final WorkStatisticsBean t, int position) {
				holder.setText(R.id.tvName, t.getUser_name());
				holder.setImage(R.id.ivLogo, t.getHead_path());
				holder.setText(R.id.tvWbAllCount, t.getWbTaskCount() + "");
				holder.setText(R.id.tvWbWaitSignCount, t.getWbUnSign() + "");
				holder.setText(R.id.tvWbWaitDetectCount, t.getWbUnTest() + "");
				holder.setText(R.id.tvWbWaitFinishCount, t.getWbComplete() + "");
				holder.setText(R.id.tvWxAllCount, t.getBxTaskCount() + "");
				holder.setText(R.id.tvWxWaitCount, t.getBxUnRepair() + "");
				holder.setText(R.id.tvWxFinishCount, t.getBxComplete() + "");
				holder.setOnClickListener(R.id.llRoot, new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						Intent intent = new Intent(v.getContext(),PersonWorkStatisticsActivity.class);
						intent.putExtra("work_user", new Gson().toJson(t));
						intent.putExtra("mouth", tvSearchDate.getText().toString());
						startActivity(intent);
					}
				});
			}
		};

		adapter = new EmptyWrapper(mCommonAdapter);

		View emptyView = inflater.inflate(R.layout.empty_view_text_and_image,
				mListView, false);
		ImageView ivEmptyTip = (ImageView) emptyView
				.findViewById(R.id.ivEmptyTip);
		TextView tvEmptyTip = (TextView) emptyView
				.findViewById(R.id.tvEmptyTip);
		ivEmptyTip.setImageResource(R.mipmap.tip_empty_huodong);
		tvEmptyTip.setText(R.string.NO_DATA);
		adapter.setEmptyView(emptyView);

		mListView.setAdapter(adapter);
		adapter.notifyDataSetChanged();
	}

	@Override
	public void onRefresh() {
		getData("");
	}

	private void getData(String month) {
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN,
				UserInfoUtil.getCurrentUserAccessToken());
		if(!TextUtils.isEmpty(month))
		{
			params.put("month", month);
		}
		VolleyRequest.StringRequestPost(this,
				WebApi.MAINTENANCE_LEADER_WORK_LIST, "", params,
				new StringInterface(this) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								String data = obj.getString("data");
								List<WorkStatisticsBean> temp = new Gson()
										.fromJson(
												data,
												new TypeToken<List<WorkStatisticsBean>>() {
												}.getType());
								mWorkStatistics.clear();
								mWorkStatistics.addAll(temp);
								adapter.notifyDataSetChanged();
							} else if (status.equals("404")
									&& info.contains("尚未登录")) {
								ToastUtil.getInstances().showMsg(
										"尚未登录或该用户在其他地方登录，请重新登录！");
								// 清除环信登录
								UserHelp.getInstance().clearUser(
										AppBase.Context, true);
								return;
							} else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
							refreshLayout.setRefreshing(false);
						}
					}

					@Override
					public void stringError(VolleyError error) {
						refreshLayout.setRefreshing(false);
						ToastUtil.getInstances().showMsg(
								R.string.err_http_response);
					}
				});
	}
	
	protected Dialog onCreateDialog() {
		return new MonPickerDialog(this, mDateSetListener, mYear, mMonth,mDay);
	}
	
	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {

		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			mYear = year;
			String mm;
			String dd;
			if (monthOfYear < 9) {
				mMonth = monthOfYear + 1;
				mm = "0" + mMonth;
			} else {
				mMonth = monthOfYear + 1;
				mm = String.valueOf(mMonth);
			}
			if (dayOfMonth <= 9) {
				mDay = dayOfMonth;
				dd = "0" + mDay;
			} else {
				mDay = dayOfMonth;
				dd = String.valueOf(mDay);
			}
			mDay = dayOfMonth;
			tvSearchDate.setText(String.valueOf(mYear) +"-" + mm);
			getData(tvSearchDate.getText().toString());
		}
	};

	@OnClick({ R.id.tvBack })
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.tvBack:
			finish();
			break;
		default:
			break;
		}
	}

	@Override
	public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
		tvSearchDate.setText(DateUtils.timeStampToStr(millseconds/1000,DateUtils.YM_FORMAT));
		getData(tvSearchDate.getText().toString());
	}
}
